package com.burst.reptile.modular.api.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.burst.reptile.common.constant.Constants;
import com.burst.reptile.common.constant.UserConstants;
import com.burst.reptile.common.utils.Pinyin4jUtil;
import com.burst.reptile.common.utils.ToolUtil;
import com.burst.reptile.framework.redis.RedisCache;
import com.burst.reptile.framework.web.controller.BaseController;
import com.burst.reptile.framework.web.entity.LayuiTreeSelect;
import com.burst.reptile.framework.web.result.LayuiResult;
import com.burst.reptile.framework.web.result.Result;
import com.burst.reptile.modular.api.vo.CascaderVo;
import com.burst.reptile.modular.zp.entity.ZpCity;
import com.burst.reptile.modular.zp.form.CityRes;
import com.burst.reptile.modular.zp.service.IZpCityService;

import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.http.HttpUtil;
import lombok.RequiredArgsConstructor;

/**
 * <p>
 * 地区列表 前端控制器
 * </p>
 *
 * @author wujin
 * @since 2020-06-18
 */
@RestController
@RequestMapping("/api/city")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ZpCityController extends BaseController {

	private final IZpCityService cityService;

	private final RedisCache redisCache;

	/**
	 * 根据父ID获取子类
	 * 
	 * @param id 父ID
	 * @return
	 */
	@GetMapping("/children/{id}")
	public Result<Object> children(@PathVariable String id) {
		return Result.success(cityService.children(id));
	}

	/**
	 * 切换站点
	 * 
	 * @param id 站点ID
	 * @return
	 */
	@PostMapping("/change/{id}")
	public Result<Object> change(@PathVariable String id, HttpServletResponse response) {
		ZpCity byId = cityService.getById(id);
		if (ToolUtil.isEmpty(byId)) {
			return Result.error("站点不存在");
		}
		String disabled = byId.getDisabled();
		if (!StrUtil.equals(disabled, "0")) {
			return Result.error("很抱歉，该站点暂未开发");
		}
		String ancestors = byId.getAncestors();
		List<String> splitTrim = StrUtil.splitTrim(ancestors, ",");
		if (splitTrim.size() != 2) {
			return Result.error("选择站点错误");
		}
		ZpCity byId2 = cityService.getById(byId.getParentId());
		// 创建cookie
		Cookie authorization = new Cookie(Constants.CITY_SITE, byId.getAid());
		authorization.setHttpOnly(true);
		authorization.setPath("/");
		response.addCookie(authorization);
		return Result.success(byId2.getName());
	}

	/**
	 * 查询站点
	 * 
	 * @param id 站点ID
	 * @return
	 */
	@GetMapping("/query")
	public Result<Object> change(@RequestParam(required = false) String citySite) {
		List<ZpCity> list = new ArrayList<>();
		if (StrUtil.isEmpty(citySite)) {
			return Result.success(list);
		}
		list = cityService
				.list(new QueryWrapper<ZpCity>().like("name", citySite).ne("parent_id", 0).eq("disabled", "0"));
		if (ToolUtil.isNotEmpty(list)) {
			list = list.stream().filter(i -> {
				List<String> splitTrim = StrUtil.splitTrim(i.getAncestors(), ",");
				return splitTrim.size() == 2;
			}).collect(Collectors.toList());
		}
		return Result.success(list);
	}

	/**
	 * 封装cascader异步请求数据
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/getDat/{id}")
	public Result<Object> getDat(@PathVariable String id) {
		List<CascaderVo> list = new ArrayList<>();
		List<ZpCity> children = cityService.children(id);
		if (ToolUtil.isNotEmpty(children)) {
			list = children.stream().map(i -> {
				return CascaderVo.builder().value(i.getAid()).label(i.getName())
						.disabled(StrUtil.equals(i.getDisabled(), "1"))
						.haveChildren(StrUtil.splitTrim(i.getAncestors(), ",").size() <= 2).build();

			}).collect(Collectors.toList());
		}
		return Result.success(list);
	}

	/**
	 * 获取部门下拉树列表
	 */
	@GetMapping("/treeselect")
	@PreAuthorize("@ss.hasPermi('zp:city:list')")
	public Result<Object> treeselect(ZpCity city) {
		Object cacheObject = redisCache.getCacheObject(Constants.CITY_KEY_TREE);
		if (ToolUtil.isEmpty(cacheObject)) {
			List<ZpCity> citys = cityService.selectCityList(city);
			List<LayuiTreeSelect> buildCityLayuiTreeSelect = cityService.buildCityLayuiTreeSelect(citys);
			redisCache.setCacheObject(Constants.CITY_KEY_TREE, buildCityLayuiTreeSelect);
			return Result.success(buildCityLayuiTreeSelect);
		}
		return Result.success(cacheObject);
	}

	/**
	 * 获取部门下拉树列表
	 */
	@GetMapping("/list")
	@PreAuthorize("@ss.hasPermi('zp:city:list')")
	public LayuiResult<Object> list(ZpCity city) {
		Page<ZpCity> page = startPage();
		Page<ZpCity> citys = cityService.getCitys(page, city);
		return LayuiResult.success(citys.getTotal(), citys.getRecords());
	}

	/**
	 * 新增站点
	 */
	@PostMapping("/add")
	@PreAuthorize("@ss.hasPermi('zp:city:add')")
	public Result<Object> add(@Validated @RequestBody ZpCity city) {
		ZpCity byId = cityService.getById(city.getAid());
		if (ToolUtil.isNotEmpty(byId)) {
			return Result.error("新增站点'" + city.getName() + "'失败，站点名称已存在");
		}
		String parentId = city.getParentId();
		if(!StrUtil.equals(parentId, "0")) {
			ZpCity byId2 = cityService.getById(parentId);
			if (ToolUtil.isEmpty(byId2)) {
				return Result.error("新增站点'" + city.getName() + "'失败，父节点名称不存在");
			}
			city.setAncestors(byId2.getAncestors() + "," + byId2.getAid());
			city.setLevelType(city.getAncestors().split(",").length + "");
		}
		if (UserConstants.NOT_UNIQUE.equals(cityService.checkCityNameUnique(city))) {
			return Result.error("新增站点'" + city.getName() + "'失败，站点名称已存在");
		}
		int insertDept = cityService.insertCity(city);
		List<ZpCity> citys = cityService.selectCityList(new ZpCity());
		List<LayuiTreeSelect> buildCityLayuiTreeSelect = cityService.buildCityLayuiTreeSelect(citys);
		redisCache.setCacheObject(Constants.CITY_KEY_TREE, buildCityLayuiTreeSelect);
		return Result.success(insertDept);
	}

	/**
	 * 修改站点
	 */
	@PutMapping("/edit")
	@PreAuthorize("@ss.hasPermi('zp:city:edit')")
	public Result<Object> edit(@Validated @RequestBody ZpCity city) {
		if (UserConstants.NOT_UNIQUE.equals(cityService.checkCityNameUnique(city))) {
			return Result.error("修改站点'" + city.getName() + "'失败，站点名称已存在");
		} else if (city.getParentId().equals(city.getAid())) {
			return Result.error("修改站点'" + city.getName() + "'失败，上级站点不能是自己");
		} else if (StrUtil.equals(UserConstants.DEPT_DISABLE, city.getDisabled())
				&& cityService.selectNormalChildrenCityById(city.getAid()) > 0) {
			return Result.error("该部门包含未停用的子站点！");
		}
		int updateDept = cityService.updateCity(city);
		List<ZpCity> citys = cityService.selectCityList(new ZpCity());
		List<LayuiTreeSelect> buildCityLayuiTreeSelect = cityService.buildCityLayuiTreeSelect(citys);
		redisCache.setCacheObject(Constants.CITY_KEY_TREE, buildCityLayuiTreeSelect);
		redisCache.deleteObject(Constants.CITY_KEY);
		return Result.success(updateDept);
	}

	/**
	 * 状态修改
	 */
	@PreAuthorize("@ss.hasPermi('zp:city:edit')")
	@PutMapping("/changeStatus")
	public Result<Object> changeStatus(@RequestBody ZpCity city) {
		if (StrUtil.equals(UserConstants.DEPT_DISABLE, city.getDisabled())
				&& cityService.selectNormalChildrenCityById(city.getAid()) > 0) {
			return Result.error("该部门包含未停用的子站点！");
		}

		int updateCityStatus = cityService.updateCityStatus(city);
		List<ZpCity> citys = cityService.selectCityList(new ZpCity());
		List<LayuiTreeSelect> buildCityLayuiTreeSelect = cityService.buildCityLayuiTreeSelect(citys);
		redisCache.setCacheObject(Constants.CITY_KEY_TREE, buildCityLayuiTreeSelect);
		redisCache.deleteObject(Constants.CITY_KEY);
		return Result.success(updateCityStatus);
	}

	/**
	 * 删除站点
	 */
	@DeleteMapping("/remove/{id}")
	@PreAuthorize("@ss.hasPermi('zp:city:remove')")
	public Result<Object> remove(@PathVariable String id) {
		if (cityService.hasChildByAid(id)) {
			return Result.error("存在下级部门,不允许删除");
		}
		int deleteCityById = cityService.deleteCityById(id);
		List<ZpCity> citys = cityService.selectCityList(new ZpCity());
		List<LayuiTreeSelect> buildCityLayuiTreeSelect = cityService.buildCityLayuiTreeSelect(citys);
		redisCache.setCacheObject(Constants.CITY_KEY_TREE, buildCityLayuiTreeSelect);
		return Result.success(deleteCityById);
	}

	/**
	 * 封装cascader异步请求数据
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("/getDatAll")
	public Result<Object> getDatAll(@RequestParam(required = false) String name, HttpServletResponse response) {
		byte[] cachobj = redisCache.getCacheObject(Constants.CITY_KEY);
		if (ToolUtil.isEmpty(cachobj)) {
			List<ZpCity> citys = cityService.list(new QueryWrapper<ZpCity>().eq("disabled", "0").orderByAsc("aid"));
			List<CascaderVo> buildCityTreeSelect = cityService.buildCityTreeSelect(citys);
			String jsonString = JSONObject.toJSONString(buildCityTreeSelect);
			byte[] gzip = ZipUtil.gzip(UnicodeUtil.toUnicode(jsonString).getBytes());
			redisCache.setCacheObject(Constants.CITY_KEY, gzip);
			return Result.success(gzip);
		}
		return Result.success(cachobj);
	}
	
	
//	@GetMapping("/addAll")
	public Result<Object> all() {
		String result1 = HttpUtil.get("http://localhost:8085/assets/json/area.json");
		List<String> s = new ArrayList<>();
		s.add("");
		String sds = "阿昌族、鄂温克族、傈僳族、水族、白族、高山族、珞巴族、塔吉克族、保安族、仡佬族、满族、塔塔尔族、布朗族、哈尼族、毛南族、土家族、布依族、哈萨克族、门巴族、土族、朝鲜族、蒙古族、佤族、达斡尔族、赫哲族、苗族、维吾尔族、傣族、回族、仫佬族、乌孜别克族 、德昂族、基诺族、纳西族、锡伯族、东乡族、京族、怒族、瑶族、侗族、景颇族、普米族、彝族、独龙族、柯尔克孜族、羌族、裕固族、俄罗斯族、拉祜族、撒拉族、藏族、鄂伦春族、黎族、畲族、壮族";
		List<String> split = StrUtil.split(sds, "、".charAt(0));
		split.add("自治州");
		split.add("自治县");
		split.add("地区");
		split.add("省");
		split.add("市");
		split.add("区");
		split.add("县");
		List<CityRes> parseArray = JSONObject.parseArray(result1, CityRes.class);
		for (CityRes cityRes : parseArray) {
			String code = cityRes.getCode();
			ZpCity zpCity = new ZpCity();
			zpCity.setAid(code);
			String name = cityRes.getName();
			zpCity.setName(name); // 名称
			String replace = name;
			for (String str : split) {
				if(replace.length() > 2) {
					replace = replace.replace(str, "");
				}
			}
			zpCity.setShortName(replace); // 简称
			String pinyinJianPin = Pinyin4jUtil.getPinyinJianPin(replace);
			List<String> splitTrim = StrUtil.splitTrim(pinyinJianPin, ",");
			if(splitTrim.size() == 1) {
				zpCity.setJianpin(splitTrim.get(0)); // 简拼
			}else {
				zpCity.setJianpin(pinyinJianPin);
			}
			String pinyin = Pinyin4jUtil.getPinyin(replace);
			List<String> splitTrim2 = StrUtil.splitTrim(pinyin, ",");
			if(splitTrim2.size() == 1) {
				zpCity.setPinyin(splitTrim2.get(0)); // 拼音
			}else {
				zpCity.setPinyin(pinyin); // 拼音
			}
			zpCity.setFirstChar(Pinyin4jUtil.getPinyinFirstToUpperCase(replace)); // 首拼
			zpCity.setAncestors("0"); // ID路径
			zpCity.setParentId("0"); // 父ID
			zpCity.setLevelType("1");
			cityService.save(zpCity);
			List<CityRes> cityList = cityRes.getCityList();
			if(ToolUtil.isNotEmpty(cityList)) {
				for (CityRes cityRes2 : cityList) {
					ZpCity zpCity2 = new ZpCity();
					String name2 = cityRes2.getName();
					String code2 = cityRes2.getCode();
					zpCity2.setAid(code2);
					zpCity2.setName(name2); // 名称
					String replace2 = name2;
					for (String str : split) {
						if(replace2.length() > 2) {
							replace2 = replace2.replace(str, "");
						}
					}
					zpCity2.setShortName(replace2); // 简称
					String pinyin2 = Pinyin4jUtil.getPinyin(replace2);
					List<String> splitTrim3 = StrUtil.splitTrim(pinyin2, ",");
					if(splitTrim3.size() == 1) {
						zpCity2.setPinyin(splitTrim3.get(0)); // 拼音
					}else {
						zpCity2.setPinyin(pinyin2); // 拼音
					}
					String pinyinJianPin2 = Pinyin4jUtil.getPinyinJianPin(replace2);
					List<String> pinyinJianPin2s = StrUtil.splitTrim(pinyinJianPin2, ",");
					if(pinyinJianPin2s.size() == 1) {
						zpCity2.setJianpin(pinyinJianPin2s.get(0)); // 简拼
					}else {
						zpCity2.setJianpin(pinyinJianPin2); // 简拼
					}
					zpCity2.setFirstChar(Pinyin4jUtil.getPinyinFirstToUpperCase(replace2)); // 首拼
					zpCity2.setAncestors("0," + code); // ID路径
					zpCity2.setParentId(code); // 父ID
					zpCity2.setLevelType("2");
					cityService.save(zpCity2);
					List<CityRes> areaList = cityRes2.getAreaList();
					if(ToolUtil.isNotEmpty(areaList)) {
						for (CityRes cityRes3 : areaList) {
							ZpCity zpCity3 = new ZpCity();
							String name3 = cityRes3.getName();
							String code3 = cityRes3.getCode();
							zpCity3.setAid(code3);
							zpCity3.setName(name3); // 名称
							// 朝鲜族自治州 土家族苗族自治州 回族自治州 藏族自治州 藏族自治州 彝族自治州 藏族羌族自治州 苗族侗族自治州 布依族苗族自治州 布依族苗族自治州
							// 维吾尔自治 回族自治州 哈萨克自治州 蒙古自治州 蒙古自治州 柯尔克孜自治州 藏族自治州 蒙古族 彝族自治州 白族自治州 傈僳族自治州 傣族自治州 壮族苗族自治州 
							// 傣族景颇族自治州 哈尼族彝族自治州
							String replace3 = name3;
							for (String str : split) {
								if(replace3.length() > 2) {
									replace3 = replace3.replace(str, "");
								}
							}
							zpCity3.setShortName(replace3); // 简称
							String pinyin3 = Pinyin4jUtil.getPinyin(replace3);
							List<String> splitTrim4 = StrUtil.splitTrim(pinyin3, ",");
							if(splitTrim4.size() == 1) {
								zpCity3.setPinyin(splitTrim4.get(0)); // 拼音
							}else {
								zpCity3.setPinyin(pinyin3); // 拼音
							}
							String pinyinJianPin3 = Pinyin4jUtil.getPinyinJianPin(replace3);
							List<String> splitTrim5 = StrUtil.splitTrim(pinyinJianPin3, ",");
							if(splitTrim5.size() == 1) {
								zpCity3.setJianpin(splitTrim5.get(0)); // 简拼
							}else {
								zpCity3.setJianpin(pinyinJianPin3); // 简拼
							}
							zpCity3.setFirstChar(Pinyin4jUtil.getPinyinFirstToUpperCase(replace3)); // 首拼
							zpCity3.setAncestors("0," + code + "," + code2); // ID路径
							zpCity3.setParentId(code2); // 父ID
							zpCity3.setLevelType("3");
							cityService.save(zpCity3);
						}
					}
				}
			}
		}
		return Result.success("ok");
	}
	

}
